import React, { useEffect, useState } from 'react'
import style from './Index.module.less'
import { Table } from 'antd'
import { getColumns } from './util'
import { awaitWrap } from '@js/tool'
import { getListRequest } from './ajax'
import SearchFrom from './components/Form/Index'
import { useDispatch } from 'react-redux'
// import { PlusOutlined } from '@ant-design/icons'
import AddModal from './components/AddModal/Index'

async function getList (condition, pageSize, current, setLoading, setList, setTotal) {
  setLoading(true)
  const [e, d] = await awaitWrap(getListRequest(condition, pageSize, current))
  setLoading(false)
  if (e === null && d !== null) {
    d.list.forEach((li, i) => {
      li.index = i + 1 + (current - 1) * pageSize
    })
    setList(d.list)
    setTotal(d.total)
  }
}

function Main ({ title }) {
  const dispatch = useDispatch()
  const [loading, setLoading] = useState(false)
  const [visible, setVisible] = useState(false)
  const [total, setTotal] = useState(0)
  const [pageSize, setPageSize] = useState(10)
  const [current, setCurrent] = useState(1)
  const [list, setList] = useState([])
  const [condition, setCondition] = useState([])
  const [version, setVersion] = useState(Date.now())
  const [pagination, setPagination] = useState({
    total,
    pageSize,
    current,
    showSizeChanger: true,
    showQuickJumper: true,
    showTotal: total => `共 ${total} 条记录`,
    size: 'small'
  })
  useEffect(() => {
    getList(condition, pageSize, current, setLoading, setList, setTotal)
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [pageSize, current, condition, version])
  useEffect(() => {
    setPagination({
      ...pagination,
      total,
      pageSize,
      current
    })
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [total, pageSize, current])
  return (
    <div className={style.container}>
      <AddModal
        visible={visible} hide={() => setVisible(false)} refreshFn={() => {
          setCurrent(1)
          setVersion(Date.now())
        }}
      />
      <div className={style['title-line']}>
        <span>{title}</span>
      </div>
      <SearchFrom onChange={(c) => { setCondition(c); setCurrent(1) }} />
      {/* <div className={style['table-btns-line']}>
        <Button type='primary' icon={<PlusOutlined />} onClick={() => setVisible(true)}>新增上报</Button>
      </div> */}
      <div className={style.table}>
        <Table rowKey='id' columns={getColumns(dispatch, () => getList(condition, pageSize, current, setLoading, setList, setTotal))} loading={loading} dataSource={list} pagination={pagination} onChange={({ current, pageSize }) => { setPageSize(pageSize); setCurrent(current) }} scroll={{ x: 1600 }} />
      </div>
    </div>
  )
}

export default Main
